import plugin from '../../lib/plugins/plugin.js'
import fs from 'fs'
import YAML from 'yaml'
let path = './config/sleep-group.yaml'//群号数据，yaml文件
const botname = global.Bot.nickname; //bot名字

if (!fs.existsSync(path)) { fs.writeFileSync(path, '') }

export class zhenxunsleep extends plugin {
  constructor() {
    super({
      name: '真寻休息',
      dsc: '仿真寻休息',
      event: 'message.group',
      priority: -99999999,
      rule: [
        {
          reg: `^#?(${botname})?(休息吧|醒来?)$`,
          fnc: 'sleep',
        },
        {
          reg: `^#?(${botname})?(在哪睡觉|去哪睡了)$`,
          fnc: 'listgroup',
        },
        {
          reg: '',
          fnc: 'monitor',
          log: false
        },
      ]
    })
  }

  async sleep(e) {
    if (!e.isMaster) { return e.reply(`只有主人才能命令${botname}哦~`, false, { at: true }) }
    let data = await getread()
    if (!data) data = [];
    if (data.indexOf(e.group_id) == -1 && e.msg.includes('休息吧')) {
      await data.push(e.group_id)
      await e.reply('那我先睡觉了...')
    }
    if (data.indexOf(e.group_id) !== -1 && e.msg.includes('醒来')) {
      await data.splice(data.indexOf(e.group_id), 1)
      await e.reply('呜..醒来了...')
    } else if (data.indexOf(e.group_id) == -1) {
      await e.reply('我还醒着呢！')
    }
    getwrite(data)
  }

  async listgroup(e) {
    let data =  getread()
    if (!data.length || !data) return e.reply(`空的记录：没有任何${botname}正在睡觉的群聊`)
    e.reply(`${botname}在这些群睡觉:\n` + data.toString().replace(/,/, '\n') + '\n' + "Created By Yunzai-Bot & js-sleep");
  }

  async monitor(e) {
    let group = await getread()
    try {
      for (let qqq of group) {
        if (e.group_id == qqq && !e.isMaster) {
          return true
        } else {
          return false
        }
      }
    } catch (e) {
      return false
    }
    return false
  }
}


/** 读取 */
function getread() {
  try {
    var fileContents = fs.readFileSync(path, 'utf8');
  } catch (e) {
    console.log(e);
    return false;
  }
  //转换
  return YAML.parse(fileContents);
}

/** 写入 */
function getwrite(data) {
  try {
    //转换
    let yaml = YAML.stringify(data);
    fs.writeFileSync(path, yaml, 'utf8');
    return true
  } catch (e) {
    //错误处理
    console.log(e);
    return false
  }
}